package com.yhl.file;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.logging.Logger;

/**
 * @author: yanghl
 * @description: TODO
 * @date: 2024/3/27 17:03
 */
@RequestMapping("/file")
@RestController
public class FileUploadController {
    private static Logger logger = Logger.getLogger(FileUploadController.class.getName());

    @Autowired
    HttpServletRequest request;
    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return new ResponseEntity<>("Please select a file to upload.", HttpStatus.BAD_REQUEST);
        }

        try {
            // 在这里处理文件保存的逻辑，例如保存到服务器的特定目录
            // 获取文件名
            String fileName = new String(file.getOriginalFilename().getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            // String fileName = file.getOriginalFilename();
            logger.info("fileName:" + fileName);
            // 指定保存文件的路径
            Path path = Paths.get("/uploads/" + fileName);
            // 确保目录存在
            Files.createDirectories(path.getParent());
            // 将文件保存到服务器
            try (InputStream inputStream = file.getInputStream()) {
                Files.copy(inputStream, path, StandardCopyOption.REPLACE_EXISTING);
            }
            return new ResponseEntity<>("You successfully uploaded '" + file.getOriginalFilename() + "'", HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
    }
}

